package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.aliyun.OSSService;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.threadlocal.UserThreadLocalUtils;
import com.heima.model.media.dtos.WmMaterialDto;
import com.heima.wemedia.entity.WmMaterial;
import com.heima.wemedia.entity.WmNewsMaterial;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.IWmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.wemedia.service.IWmNewsMaterialService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author heima
 * @since 2021-03-15
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements IWmMaterialService {

    @Autowired
    private OSSService ossService;

    @Override
    public String uploadPicture(MultipartFile multipartFile) {
        //上传图片到阿里云oss服务
        try {
            //获取用户id
            Integer userId = UserThreadLocalUtils.getUserId();
            if(userId==null){
                throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
            }
            String url = ossService.upload(multipartFile);
            //将上传的图片素材记录到数据库中
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(userId);
            wmMaterial.setUrl(url);
            wmMaterial.setType(0);// 0代表是图片素材
            wmMaterial.setIsCollection(false);//未收藏状态
            wmMaterial.setCreatedTime(new Date());
            //保存到数据库
            boolean b = save(wmMaterial);
            if(!b){
                throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"保存素材数据失败");
            }
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"图片上传失败");
        }
    }

    @Override
    public PageResult<WmMaterial> findByPage(WmMaterialDto dto) {
        //获取当前用户
        Integer userId = UserThreadLocalUtils.getUserId();
        if(userId==null){
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //组装分页条件
        Page<WmMaterial> page = new Page<>(dto.getPage(),dto.getSize());
        //组装是否收藏条件
        String isCollection = dto.getIsCollection();
        QueryWrapper<WmMaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(WmMaterial::getUserId,userId);
        Boolean collection=null;
        if(isCollection!=null){
            if("0".equals(isCollection)){
                collection=false;
            }else {
                collection=true;
            }
            queryWrapper.lambda().eq(WmMaterial::getIsCollection,collection);
        }
        //执行查询
        IPage<WmMaterial> iPage = this.page(page, queryWrapper);
        if(CollectionUtils.isEmpty(iPage.getRecords())){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"素材数据不存在");
        }

        return new PageResult<>(dto.getPage(),dto.getSize(),iPage.getTotal(),iPage.getRecords());
    }

    @Override
    public void updateIsCollection(Integer id, boolean isCollection) {
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setId(id);
        wmMaterial.setIsCollection(isCollection);
        boolean b = updateById(wmMaterial);
        if(!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"收藏状态更新失败");
        }
    }

    @Autowired
    private IWmNewsMaterialService wmNewsMaterialService;

    @Override
    public void deletePic(Integer id) {
        //获取当前用户
        Integer userId = UserThreadLocalUtils.getUserId();
        if(userId==null){
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //查询素材是否被引用
        QueryWrapper<WmNewsMaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(WmNewsMaterial::getMaterialId,id);
        //执行查询
        int count = wmNewsMaterialService.count(queryWrapper);
        if(count>0){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"素材被引用，不能删除");
        }
        //查询素材数据，截取图片名称，删除oss服务器图片数据
        QueryWrapper<WmMaterial> materialQueryWrapper = new QueryWrapper<>();
        materialQueryWrapper.lambda().eq(WmMaterial::getId,id).eq(WmMaterial::getUserId,userId);
        WmMaterial wmMaterial = this.getOne(materialQueryWrapper);
        if(wmMaterial==null){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"素材数据不存在");
        }
        //获取图片名称
        //url示例：https://javaee9.oss-cn-beijing.aliyuncs.com/e7163ae7-7b5c-4aaf-9069-dc147a4e3628.jpg
        String imageName = StringUtils.substringAfterLast(wmMaterial.getUrl(), "/");
        //执行删除阿里云oss图片
        ossService.deleteFile(imageName);
        //删除素材表数据
        removeById(id);
    }
}
